package com.kin207.netty;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.concurrent.Executors;

import com.kin207.netty.handle.MessageHandles;
import com.kin207.netty.handle.impl.GroupAddMessageHandle;
import com.kin207.netty.handle.impl.GroupMessageHandle;
import com.kin207.netty.handle.impl.GroupRemoveMessageHandle;
import com.kin207.netty.handle.impl.P2pMessageHandle;
import com.kin207.netty.handle.impl.SetNameMessageHandle;
import com.kin207.netty.handle.impl.SystemMessageHandle;

public class UdpClient {

	public static void main(String[] args) throws UnknownHostException, IOException, InterruptedException {
		int port = args.length==1?Integer.parseInt(args[0]):8378;
		port = args.length>1?Integer.parseInt(args[1]):8378;
		String ip = args.length>1?args[0]:"127.0.0.1";
		System.out.println("conntion "+ip+":"+port+"...");
		InetAddress addr = InetAddress.getByName(ip);
		final DatagramSocket client = new DatagramSocket();
		
		System.out.println("conntion success");
		System.out.println("命令列表:");
		MessageHandles.printHandles();
		
		Executors.newSingleThreadExecutor().submit(new Runnable() {
			public void run() {
				try {
					byte[] recvBuf = new byte[1024*10];
			        DatagramPacket recvPacket = new DatagramPacket(recvBuf , recvBuf.length);
					while(true){
						client.receive(recvPacket);
						String msg = new String(recvPacket.getData() , 0 ,recvPacket.getLength());
						System.out.println("server:"+msg);
					}
				} catch (Exception e) {
					e.printStackTrace();
				} 
				
			}
		});
		
		Scanner scann = new Scanner(System.in);
		while(true){
			System.out.print("请输入:");
			String msg = scann.nextLine();
		
			byte[] sendBuf = msg.getBytes();
			DatagramPacket sendPacket = new DatagramPacket(sendBuf ,sendBuf.length , addr , port);
			client.send(sendPacket);
		}
	}

}
